<?php

/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/11/26
 * Time: 11:51 AM
 */
class ThrottleUtil
{
    /**
     * @param $ip
     * @return bool
     * ip限制,如果连续登陆五次失败,10分钟后再操作
     */
    const IP_LOCK_TIME_KEY = "ip_lock_time_key";
    const IP_LOCK_COUNT_KEY = "ip_lock_count_key";
    const LOCK_EXPIRE_TTL = 10*60;//ip限制登陆时间 十分钟
    const LOGIN_FAIL_EXPIRE_TTL = 5*60;//ip限制登陆时间 十分钟
    public  function verifyLogin($ip){
        $ip_lock = \think\Cache::get(self::IP_LOCK_TIME_KEY.$ip);
        if($ip_lock&&$ip_lock > 5){
            return false;
        }
        return true;
    }

    /**
     * @param $ip
     * 统计登陆失败次数
     */
    public  function addFailLoginTimes($ip){
        $fail_login_times = \think\Cache::get(self::IP_LOCK_COUNT_KEY.$ip);
        if($fail_login_times && $fail_login_times < 5){
            $fail_login_times++;
            \think\Cache::set(self::IP_LOCK_COUNT_KEY.$ip,$fail_login_times,self::LOGIN_FAIL_EXPIRE_TTL);
            return $fail_login_times;
        }elseif ($fail_login_times == 0 || $fail_login_times == null ){
            \think\Cache::set(self::IP_LOCK_COUNT_KEY.$ip,1,self::LOGIN_FAIL_EXPIRE_TTL);
            return 1;
        }
        elseif($fail_login_times && $fail_login_times >= 5){
            if(\think\Cache::get(self::IP_LOCK_TIME_KEY.$ip)>5){
                return 6;
            }else{
                \think\Cache::set(self::IP_LOCK_TIME_KEY.$ip,6,self::LOCK_EXPIRE_TTL);
                return 6;
            }


        }

    }
}